package com.xl.sharedModel;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * JdkVersion: 1.8
 * Author: lei·xie
 * Created: 2024/8/7 0007 10:44
 * Description: 共享模型 卖票
 */
@Slf4j(topic = "c.Test6")
public class Test06 {

    public static void main(String[] args) throws InterruptedException {
        TickedWindow tickedWindow = new TickedWindow(10000);
        List<Thread> list = new ArrayList<>();
        //用来存储卖出去多少张票
        List<Integer> sellCount = new Vector<>();
        for (int i=0; i<2000; i++) {
            Thread t = new Thread(()->{
                //分析这里的竞态条件
                int count = tickedWindow.sell(randomAmount());
                sellCount.add(count);
            });
            list.add(t);
            t.start();
        }
        //等待所以的线程执行完毕
        list.forEach((t)->{
            try {
                t.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        //统计卖出去的票数
        log.debug("sell count: {}",sellCount.stream().mapToInt(c->c).sum());
        //剩余票数
        log.debug("remainder count: {}",tickedWindow.getCount());
    }

    //Random为线程安全 随机1-5
    public static int randomAmount() {
        return new Random().nextInt(5)+1;
    }
}

@Getter
class TickedWindow {
    private int count;
    public TickedWindow(int count) {
        this.count = count;
    }

    public synchronized int sell(int amount) {
        if (count >= amount) {
            count -= amount;
            return amount;
        } else {
            return 0;
        }
    }
}
